package com.hsz.email.controller;

import com.hsz.email.pojo.User;
import com.hsz.email.util.MailUtil;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {
    User user = new User();
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String username,String password){
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        if (this.user.getUsername().equals(username) && this.user.getPassword().equals(password)){
            System.out.println("账号密码正确");
            return "true";
        }else {
            System.out.println("账号密码错误");
            return "false";
        }
    }
    @RequestMapping(value = "/verification",method = RequestMethod.POST)
    public String verification(String email,String username) throws Exception {
        System.out.println("发送邮件");
        String verification = randomStr(4);
        System.out.println("验证码为 = " + verification);
        user.setVerification(verification);
        MailUtil.mail(email, username,"用户验证",verification );
        return "true";

    }

    @ResponseBody
    @RequestMapping("/registered")
    public String registered(String username, String password, String email, String verification){
        System.out.println("verification = " + verification);
        System.out.println("user.getVerification() = " + user.getVerification());
        if (this.user.getVerification().equals(verification)){
            this.user.setUsername(username);
            this.user.setPassword(password);
            return "true";
        }else {
            return "false";
        }
    }

    private String randomStr(int n) {
        String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        String str2 = "";
        int len = str1.length() - 1;
        double r;
        for (int i = 0; i < n; i++) {

            r = (Math.random()) * len;
            str2 = str2 + str1.charAt((int) r);
        }
        return str2;
    }

}
